#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Joycon Controller Usage Example
Joycon手柄读取器使用示例

Author: Yinchuan Li
Date: 2025-07-30
"""

import time
import sys
import os

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def example_basic_usage():
    """基础使用示例"""
    print("=== 基础使用示例 ===")
    
    try:
        from read_joycon import JoyconControllerReader
        
        # 创建读取器
        controller = JoyconControllerReader()
        
        print("开始读取Joycon数据...")
        print("按 Ctrl+C 退出")
        
        # 读取5次数据
        for i in range(5):
            data = controller.read_inputs()
            if data:
                print(f"\n--- 第 {i+1} 次读取 ---")
                
                # 显示按钮状态
                active_buttons = [btn for btn, info in data['buttons'].items() if info['pressed']]
                if active_buttons:
                    print(f"按下的按钮: {active_buttons}")
                
                # 显示摇杆状态
                for axis_id, axis_info in data['axes'].items():
                    if abs(axis_info['value']) > 0.1:
                        print(f"摇杆 {axis_info['name']}: {axis_info['value']:.3f}")
                
                # 显示陀螺仪数据
                gyro = data['gyroscope']
                if abs(gyro.magnitude) > 1.0:
                    print(f"陀螺仪活动: X={gyro.x:.2f}, Y={gyro.y:.2f}, Z={gyro.z:.2f} °/s")
                
                # 显示加速度计数据
                accel = data['accelerometer']
                print(f"加速度计: 俯仰角={accel.pitch:.1f}°, 横滚角={accel.roll:.1f}°")
            
            time.sleep(1)
        
        print("\n基础使用示例完成")
        
    except Exception as e:
        print(f"基础使用示例失败: {e}")

def example_advanced_usage():
    """高级使用示例"""
    print("\n=== 高级使用示例 ===")
    
    try:
        from joycon_advanced import AdvancedJoyconReader
        
        # 创建高级读取器
        reader = AdvancedJoyconReader()
        
        # 询问是否校准
        print("是否要校准传感器？(y/n): ", end="")
        try:
            import msvcrt  # Windows
            if msvcrt.getch().decode().lower() == 'y':
                print("\n开始校准...")
                reader.calibrate_sensors(duration=3.0)
        except ImportError:
            try:
                import tty
                import termios
                
                # Linux/Mac
                fd = sys.stdin.fileno()
                old_settings = termios.tcgetattr(fd)
                try:
                    tty.setraw(sys.stdin.fileno())
                    ch = sys.stdin.read(1)
                    if ch.lower() == 'y':
                        print("\n开始校准...")
                        reader.calibrate_sensors(duration=3.0)
                finally:
                    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            except:
                pass
        
        print("开始读取数据...")
        print("按 Ctrl+C 退出")
        
        # 读取5次数据
        for i in range(5):
            state = reader.read_joycon_data()
            if state:
                print(f"\n--- 第 {i+1} 次读取 ---")
                
                # 显示按钮状态
                active_buttons = [btn for btn, pressed in state.buttons.items() if pressed]
                if active_buttons:
                    print(f"按下的按钮: {active_buttons}")
                
                # 显示摇杆状态
                for stick_name, (x, y) in state.sticks.items():
                    if abs(x) > 0.1 or abs(y) > 0.1:
                        print(f"{stick_name}摇杆: X={x:.3f}, Y={y:.3f}")
                
                # 显示传感器数据
                gyro = state.gyroscope
                accel = state.accelerometer
                
                if abs(gyro.magnitude) > 2.0:
                    print(f"陀螺仪活动: {gyro.magnitude:.2f} °/s")
                
                if abs(accel.magnitude - 9.81) > 1.0:
                    print(f"加速度变化: {accel.magnitude:.2f} m/s²")
                
                # 显示电池状态
                if state.battery_level > 0:
                    print(f"电池电量: {state.battery_level:.1f}%")
            
            time.sleep(1)
        
        print("\n高级使用示例完成")
        
    except Exception as e:
        print(f"高级使用示例失败: {e}")

def example_gesture_recognition():
    """手势识别示例"""
    print("\n=== 手势识别示例 ===")
    
    try:
        from joycon_advanced import AdvancedJoyconReader
        
        reader = AdvancedJoyconReader()
        
        print("开始手势识别...")
        print("请尝试以下手势:")
        print("1. 挥手 (快速左右移动)")
        print("2. 点头 (上下点头)")
        print("3. 旋转 (绕Z轴旋转)")
        print("按 Ctrl+C 退出")
        
        gesture_count = 0
        
        for i in range(30):  # 运行30秒
            state = reader.read_joycon_data()
            if state:
                gyro = state.gyroscope
                accel = state.accelerometer
                
                # 检测挥手手势 (X轴加速度变化)
                if abs(accel.x) > 5.0:
                    print("检测到挥手手势!")
                    gesture_count += 1
                
                # 检测点头手势 (Y轴加速度变化)
                if abs(accel.y) > 5.0:
                    print("检测到点头手势!")
                    gesture_count += 1
                
                # 检测旋转手势 (Z轴角速度)
                if abs(gyro.z) > 30.0:
                    print("检测到旋转手势!")
                    gesture_count += 1
            
            time.sleep(1)
        
        print(f"\n手势识别完成，共检测到 {gesture_count} 个手势")
        
    except Exception as e:
        print(f"手势识别示例失败: {e}")

def example_robot_control():
    """机器人控制示例"""
    print("\n=== 机器人控制示例 ===")
    
    try:
        from joycon_advanced import AdvancedJoyconReader
        
        reader = AdvancedJoyconReader()
        
        print("开始机器人控制模拟...")
        print("使用摇杆控制移动，陀螺仪控制旋转")
        print("按 Ctrl+C 退出")
        
        for i in range(20):  # 运行20秒
            state = reader.read_joycon_data()
            if state:
                # 摇杆控制移动
                left_stick = state.sticks.get('left', (0, 0))
                x, y = left_stick
                
                if abs(x) > 0.1 or abs(y) > 0.1:
                    print(f"移动命令: 前进={y:.2f}, 左右={x:.2f}")
                
                # 陀螺仪控制旋转
                gyro = state.gyroscope
                if abs(gyro.z) > 5.0:
                    direction = "左转" if gyro.z > 0 else "右转"
                    print(f"旋转命令: {direction} ({abs(gyro.z):.1f} °/s)")
                
                # 按钮控制
                if any(state.buttons.values()):
                    active_buttons = [btn for btn, pressed in state.buttons.items() if pressed]
                    print(f"按钮命令: {active_buttons}")
            
            time.sleep(0.5)
        
        print("\n机器人控制示例完成")
        
    except Exception as e:
        print(f"机器人控制示例失败: {e}")

def main():
    """主函数"""
    print("Joycon Controller Usage Examples")
    print("=" * 50)
    
    # 检查依赖
    try:
        import pygame
        print("✓ pygame 已安装")
    except ImportError:
        print("✗ pygame 未安装，请先安装: pip install pygame")
        return
    
    try:
        import numpy as np
        print("✓ numpy 已安装")
    except ImportError:
        print("✗ numpy 未安装，请先安装: pip install numpy")
        return
    
    print("\n开始运行示例...")
    
    # 运行各种示例
    examples = [
        ("基础使用", example_basic_usage),
        ("高级使用", example_advanced_usage),
        ("手势识别", example_gesture_recognition),
        ("机器人控制", example_robot_control)
    ]
    
    for example_name, example_func in examples:
        try:
            example_func()
            print(f"\n{example_name}示例完成")
        except KeyboardInterrupt:
            print(f"\n{example_name}示例被用户中断")
        except Exception as e:
            print(f"\n{example_name}示例失败: {e}")
        
        # 询问是否继续
        if example_name != examples[-1][0]:  # 不是最后一个示例
            print("\n按 Enter 继续下一个示例，或按 Ctrl+C 退出...")
            try:
                input()
            except KeyboardInterrupt:
                print("\n用户退出")
                break
    
    print("\n所有示例完成！")

if __name__ == "__main__":
    main() 